<template>
  <div class="card" style="margin-bottom: 5px">
    <el-input clearable @clear="load" style="width: 260px;margin-right: 5px" v-model="data.title"
              placeholder="请输入公告标题" :prefix-icon="Search"></el-input>
    <el-input clearable @clear="load" style="width: 260px;margin-right: 5px"
              v-model="data.content" placeholder="请输入公告内容" :prefix-icon="Search"></el-input>
    <el-button type="primary" @click="load">查询</el-button>
    <el-button @click="reset">重置</el-button>
  </div>

  <div class="card" style="margin-bottom: 5px">
    <el-button type="primary" @click="handleAdd">新增</el-button>
    <el-button type="danger" @click="deleteBatch">批量删除</el-button>

  </div>

  <div class="card" style="margin-bottom: 5px">
    <el-table :data="data.tableDate" style="width: 100%"
              :header-cell-style="{fontWeight:'bold',color:'#333'}"
              @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55%"></el-table-column>
      <el-table-column prop="title" label="公告标题"></el-table-column>
      <el-table-column prop="content" label="公告内容">
        <template v-slot="scope">
          <el-button type="primary" @click="vierContent(scope.row.content,scope.row.title)">
            点击查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="categoryTitle" label="公告分类"></el-table-column>
      <el-table-column prop="time" label="公告时间"></el-table-column>


      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" icon="Edit" circle @click="handleEdit(scope.row)"></el-button>
          <el-button type="danger" icon="Delete" circle @click="del(scope.row.id)"></el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <div class="card">
    <el-config-provider :locale="zhCn">
      <el-pagination background layout="prev,pager, next,sizes,jumper,total"
                     :total="data.total"
                     v-model:page-size="data.pageSize"
                     @size-change="load"
                     :page-size="[5,10,20]"
                     v-model:current-page="data.pageNum"
                     @current-change="load"
                     small>

      </el-pagination>
    </el-config-provider>
    <el-dialog v-model="data.formVisible" title="公告信息" width="700" destroy-on-close>
      <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="80px"
               style="padding: 20px 30px 0 0">

        <el-form-item prop="title" label="标题">
          <el-input v-model="data.form.title" autocomplete="off" placeholder="请输入公告标题"/>
        </el-form-item>
        <el-form-item prop="categoryId" label="分类">
          <el-select v-model="data.form.categoryId" placeholder="请选择公告分类">
            <el-option v-for="item in data.categoryId"
                       :key="item.id"
                       :label="item.title"
                       :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="content" label="内容">
          <div style="border: 1px solid #ccc;width: 100%">
            <Toolbar style="border-bottom: 1px solid #ccc;"
                     :editor="editorRef"
                     :mode="mode"
            />
            <Editor style="height: 500px;overflow-y: hidden"
                    v-model="data.form.content"
                    :mode="mode"
                    :defaultConfig="editorConfig"
                    @onCreated="handleCreated"
            />

          </div>
        </el-form-item>

      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="data.viewVisible" :title="data.title1" width="800" destroy-on-close>
      <div v-html="data.content1"></div>
    </el-dialog>

  </div>


</template>
<script setup>

import {Search} from "@element-plus/icons-vue";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import {onBeforeUnmount, reactive, ref, shallowRef} from "vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {Editor, Toolbar} from "@wangeditor/editor-for-vue";
import '@wangeditor/editor/dist/css/style.css'

const formRef = ref()

const data = reactive({
  categoryId: [{id: 1, title: '系统更新'}
    , {id: 2, title: '优惠福利'}
    , {id: 3, title: '旅游天下'}
    , {id: 4, title: '新闻财经'}
    , {id: 5, title: '动物风波'}
  ],
  user: JSON.parse(localStorage.getItem('code_user') || '{}'),
  title: null,
  content: null,
  title1: null,
  content1: null,
  formVisible: false,
  viewVisible: false,
  form: {},
  rows: [],
  ids: [],
  rules: {
    title: [
      {required: true, message: "请填写公告标题", trigger: "blur"},
    ],
    content: [
      {required: true, message: "请填写公告内容", trigger: "blur"},
    ], categoryId: [
      {required: true, message: "请选择公告分类", trigger: "blur"},
    ],

  },
  tableDate: [],
  pageSize: 10,
  pageNum: 1,
  total: 10,
})

const editorRef = shallowRef()
const mode = 'default'
const editorConfig = {
  MENU_CONF: {
    uploadImage: {
      server: 'http://localhost:8080/files/notice/media/upload',
      fieldName: 'file',
      maxFileSize: 5 * 1024 * 1024, // 5M
      allowedFileTypes: ['image/*'],
      headers: {
        token: data.user.token,
      },
      onSuccess(file, res) {
        console.log(`${file.name} 上传成功`, res)
      },
      onFailed(file, res) {
        console.log(`${file.name} 上传失败`, res)
      },
      onError(file, err, res) {
        console.log(`${file.name} 上传出错`, err, res)
      }
    }
  }, placeholder: '请输入内容...',
}


onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor === null || !editor) return
  editor.destroy()
})


const handleCreated = (editor) => {
  editorRef.value = editor;
}

const load = () => {
  request.get('notice/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      title: data.title,
      content: data.content,
    }
  }).then(res => {
    if (res.code === 200) {
      data.total = res.data.total;
      data.tableDate = res.data.list;
      data.pageNum = res.data.pageNum;
      data.pageSize = res.data.pageSize;
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const reset = () => {
  data.title = null;
  data.content = null;
}

const handleAdd = () => {
  data.formVisible = true;
  data.form = {}
}

load()

const add = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      request.post('/notice/add', data.form).then(res => {
        if (res.code === 200) {
          data.formVisible = false;
          ElMessage.success('新增成功')
          load()

        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true;
}

const update = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      request.put('/notice/update', data.form).then(res => {
        if (res.code === 200) {
          data.formVisible = false;
          ElMessage.success('修改成功')
          load()

        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}
const save = () => {
  data.form.id ? update() : add()
}


const del = (id) => {
  ElMessageBox.confirm('确认删除该数据？', '删除确认', {type: 'warning'}).then(res => {
    request.delete('/notice/delete' + id).then(res => {
      if (res.code === 200) {
        ElMessage.success('删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
  })
}

const handleSelectionChange = (rows) => {
  data.rows = rows;
  data.ids = data.rows.map(v => v.id);
}
const deleteBatch = () => {
  if (data.rows.length === 0) {
    ElMessage.warning('请选择要删除的数据！')
    return
  }
  ElMessageBox.confirm('确认删除数据？', '删除确认', {type: 'warning'}).then(res => {
    request.delete('/notice/deleteBatch', {data: data.rows}).then(res => {
      if (res.code === 200) {
        ElMessage.success('批量删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
  })
}

const vierContent = (content, title) => {
  data.content1 = content;
  data.title1 = title;
  data.viewVisible = true;
}

</script>
